/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testing.jee.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;

/**
 *
 * @author kreisera
 */
public class DurationUtil {
    
    private final static Pattern dayPattern = Pattern.compile("(\\d+)d");
    private final static Pattern hourPattern = Pattern.compile("(\\d+)h");
    private final static int HOURS_PER_DAY = 8;
    private final static Logger logger = Logger.getLogger(DurationUtil.class);
    
    public static int convertToHours(String string) {
        Matcher dayMatcher = dayPattern.matcher(string);
        Matcher hourMatcher = hourPattern.matcher(string);
        int parsedDuration = 0;
        if (dayMatcher.find()) {
            if (dayMatcher.group(1) != null) {
                parsedDuration += Integer.parseInt(dayMatcher.group(1)) * HOURS_PER_DAY;
            }
        }
        if (hourMatcher.find()) {
            if (hourMatcher.group(1) != null) {
                parsedDuration += Integer.parseInt(hourMatcher.group(1));
            }
        }
        if (parsedDuration == 0) {
            try {
                parsedDuration = Integer.parseInt(string);
            } catch (Exception ex) {
                logger.error(ex);
            }
        }
        return parsedDuration;
    }

    public static String serializeDuration(int duration) {
        int days = duration / HOURS_PER_DAY;
        int restHours = duration % HOURS_PER_DAY;
        String serializedDuration = "";
        if (days > 0) {
            serializedDuration += (days + "d");
        }
        if (restHours > 0) {
            if (days > 0) {
                serializedDuration += " ";
            }
            serializedDuration += (restHours + "h");
        }
        if (serializedDuration.equals(""))
            serializedDuration = "0h";
        return serializedDuration;
    }
}
